//
//  QQAutoSizeLabel.m
//  Test
//
//  Created by mac  on 14-6-28.
//  Copyright (c) 2014年 qiuyan. All rights reserved.
//

#import "QQAutoSizeLabel.h"

#import "MacroDefinition.h"


@implementation CusLab

-(void)setHighlighted:(BOOL)highlighted{
    [super setHighlighted:highlighted];
    if (highlighted) {
        self.backgroundColor = UIColorFromRGB(0x21a4eb);
    }else{
        self.backgroundColor = [UIColor whiteColor];
    }
}
@end



@interface QQAutoSizeLabel()
{
    CGFloat contentHeight;
}
@property (nonatomic, retain) UIView *containView;
@property (nonatomic, retain) NSMutableArray * tempArray;
@property (nonatomic, retain) NSMutableArray * allViewArray;

@end

@implementation QQAutoSizeLabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

-(void)setHotViewWithArray:(NSArray*)resultArray andSampleLabelFont:(CGFloat)fontSize height:(CGFloat)labelHeight{
        
    _containView = [[UIView alloc] initWithFrame:self.bounds];
    self.containView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.containView];
    
    UIFont * font = UIFontSize(fontSize);
    float height = 0;
    float labelWidth = 0;
    UIView * previousLabel = nil;
    
    _tempArray = [[NSMutableArray alloc] initWithCapacity:5];
    _allViewArray  = [[NSMutableArray alloc]init];
    for (int i=0;i<resultArray.count;i++) {
        //创建标签
//        NSDictionary * dic = [resultArray objectAtIndex:i];
        NSString * labelTitle = [resultArray objectAtIndex:i];
        
        CGSize size = [labelTitle sizeWithAttributes:@{NSFontAttributeName:font}];
        labelWidth = size.width + 20;
        height = labelHeight + 4;
        if (labelWidth > 300) {
            size = [labelTitle sizeWithFont:font constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
            labelWidth = 300;
            height = size.height + 5;
        }
        
        int tag = i + 100;

        UIImageView * adopLabel = [self createHotLabelWithPreviousLabel:previousLabel andText:labelTitle andWidth:labelWidth andHeight:height andLabTag:tag];
        //  调色
        adopLabel.tag = i;
        //添加位置
        if (adopLabel.frameright > self.containView.frameright) { //下一行(需要换行)
            float width = self.containView.framewidth - previousLabel.frameright;
            //开始布局
            [self layoutLabelWithArray:_tempArray andWidth:width andIsLastLine:NO];
            [_tempArray removeAllObjects];
            adopLabel.frame = CGRectMake(0, previousLabel.framebottom+15.0f, adopLabel.framewidth, height);
            [self.containView addSubview:adopLabel];
        }else{//不变行（不需要换行）
            [_tempArray addObject:adopLabel];
            [self.containView addSubview:adopLabel];
        }
        previousLabel = adopLabel;
    }
    self.containView.frameheight = previousLabel.framebottom + 10.0f;
    
    if (previousLabel.framebottom > 0) {
        contentHeight = previousLabel.framebottom + 10;
    }else {
        contentHeight = height;
    }
    if (self.containViewHeightBlock) {
        self.containViewHeightBlock(self.containView.frameheight);
    }
    
    
    if (_allViewArray.count > 0) {
        UIView *tempView = [_allViewArray objectAtIndex:0];
        CusLab * labelView = [[tempView subviews] lastObject];
//        tempView.backgroundColor = [UIColor lightGrayColor];
        labelView.textColor = [UIColor darkGrayColor];
    }
    
}

-(void)setSearchHotViewWithArray:(NSArray*)resultArray andSampleLabelFont:(CGFloat)fontSize height:(CGFloat)labelHeight{
    
    _containView = [[UIView alloc] initWithFrame:self.bounds];
    self.containView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.containView];
    
    UIFont * font = UIFontSize(fontSize);
    float height = 0;
    float labelWidth = 0;
    UIView * previousLabel = nil;
    
    _tempArray = [[NSMutableArray alloc] initWithCapacity:5];
    _allViewArray  = [[NSMutableArray alloc]init];
    for (int i=0;i<resultArray.count;i++) {
        //创建标签
        //        NSDictionary * dic = [resultArray objectAtIndex:i];
        NSDictionary  *tempDic = [resultArray  objectAtIndex:i];
        
        NSString * labelTitle = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"searchWords"]];
        
        CGSize size = [labelTitle sizeWithAttributes:@{NSFontAttributeName:font}];
        labelWidth = size.width + 20;
        height = labelHeight + 4;
        if (labelWidth > 300) {
            size = [labelTitle sizeWithFont:font constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
            labelWidth = 300;
            height = size.height + 5;
        }
        
        int tag = i + 100;
        
        UIImageView * adopLabel = [self createSearchHotLabelWithPreviousLabel:previousLabel andText:labelTitle andWidth:labelWidth andHeight:height andLabTag:tag andDic:tempDic];
        //  调色
        
        adopLabel.tag = i;
        //添加位置
        if (adopLabel.frameright > self.containView.frameright) { //下一行(需要换行)
            float width = self.containView.framewidth - previousLabel.frameright;
            //开始布局
            [self layoutLabelWithArray:_tempArray andWidth:width andIsLastLine:NO];
            [_tempArray removeAllObjects];
            adopLabel.frame = CGRectMake(0, previousLabel.framebottom+15.0f, adopLabel.framewidth, height);
            [self.containView addSubview:adopLabel];
        }else{//不变行（不需要换行）
            [_tempArray addObject:adopLabel];
            [self.containView addSubview:adopLabel];
        }
        previousLabel = adopLabel;
    }
    self.containView.frameheight = previousLabel.framebottom + 10.0f;
    
    if (previousLabel.framebottom > 0) {
        contentHeight = previousLabel.framebottom + 10;
    }else {
        contentHeight = height;
    }
    if (self.containViewHeightBlock) {
        self.containViewHeightBlock(self.containView.frameheight);
    }
    
    
//    if (_allViewArray.count > 0) {
//        UIView *tempView = [_allViewArray objectAtIndex:0];
//        CusLab * labelView = [[tempView subviews] lastObject];
//        //        tempView.backgroundColor = [UIColor lightGrayColor];
//        
//        labelView.textColor = [UIColor darkGrayColor];
//    }
    
}

//创建标签
- (UIImageView *)createSearchHotLabelWithPreviousLabel:(UIView*)previousLabel
                                         andText:(NSString*)text
                                        andWidth:(float)width
                                       andHeight:(float)height
                                       andLabTag:(int)tag
                                       andDic:(NSDictionary  *)dictionary
{
    CGRect frame;
    if (previousLabel == nil) {
        frame = CGRectMake(0.0f, 0.0f, width, height);
        
    }else{
        frame = CGRectMake(previousLabel.frameright + 10, previousLabel.frametop, width, height);
    }
    CusLab *adopLabel = [[CusLab alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    adopLabel.highlightedTextColor = UIColorFromRGB(0xffffff);
    adopLabel.layer.masksToBounds=YES;
    adopLabel.layer.cornerRadius=12;
    adopLabel.layer.borderColor=UIColorFromRGB(0x999999).CGColor;
    adopLabel.layer.borderWidth=0.5f;
    adopLabel.backgroundColor = [UIColor clearColor];
    adopLabel.font = [UIFont systemFontOfSize:13];
    adopLabel.text = text;
    adopLabel.tag = tag;
    if (height > 27) {
        adopLabel.framewidth = width - 10;
    }
    adopLabel.textAlignment = NSTextAlignmentCenter;
    adopLabel.autoresizesSubviews = YES;
    adopLabel.numberOfLines = 0;
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:frame];
    adopLabel.framewidth = imageView.framewidth;
    imageView.backgroundColor=[UIColor whiteColor];
    imageView.userInteractionEnabled = YES;
    [imageView addSubview:adopLabel];
    
    if ([dictionary  objectForKey:@"url"] && ![[dictionary  objectForKey:@"url"]  isEqual:[NSNull  null]] && ![[dictionary  objectForKey:@"url"] isEqual:@""]) {
        adopLabel.textColor = RGB(164, 33, 33);
    }else {
        adopLabel.textColor = RGB(76, 76, 76);
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(taplabel:) ];
    [imageView addGestureRecognizer:tap];
    
    [_allViewArray addObject:imageView];
    
    return imageView ;
}


//创建标签
- (UIImageView *)createHotLabelWithPreviousLabel:(UIView*)previousLabel
                                         andText:(NSString*)text
                                        andWidth:(float)width
                                       andHeight:(float)height
                                       andLabTag:(int)tag
{
    CGRect frame;
    if (previousLabel == nil) {
        frame = CGRectMake(0.0f, 0.0f, width, height);
        
    }else{
        frame = CGRectMake(previousLabel.frameright + 10, previousLabel.frametop, width, height);
    }
    CusLab *adopLabel = [[CusLab alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    adopLabel.highlightedTextColor = UIColorFromRGB(0xffffff);
    adopLabel.layer.masksToBounds=YES;
    adopLabel.layer.cornerRadius=12;
    adopLabel.layer.borderColor=UIColorFromRGB(0x999999).CGColor;
    adopLabel.layer.borderWidth=0.5f;
    adopLabel.backgroundColor = [UIColor whiteColor];
    adopLabel.font = [UIFont systemFontOfSize:11];
    adopLabel.text = text;
    adopLabel.tag = tag;
    if (height > 27) {
        adopLabel.framewidth = width - 10;
    }
    adopLabel.textAlignment = NSTextAlignmentCenter;
    adopLabel.textColor = UIColorFromRGB(0x999999);
    adopLabel.autoresizesSubviews = YES;
    adopLabel.numberOfLines = 0;
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:frame];
    adopLabel.framewidth = imageView.framewidth;
    imageView.backgroundColor=[UIColor whiteColor];
    
    imageView.userInteractionEnabled = YES;
    [imageView addSubview:adopLabel];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(taplabel:) ];
    [imageView addGestureRecognizer:tap];
    
    [_allViewArray addObject:imageView];

    return imageView ;
}

//布局标签
- (void)layoutLabelWithArray:(NSMutableArray *)labelArray andWidth:(float)width andIsLastLine:(BOOL)lastLine{
    NSRange arrayRange;
    arrayRange.location = 0;
    if (lastLine) {
        arrayRange.length = labelArray.count;
    }else{
        arrayRange.length = labelArray.count;
    }
    NSArray * layoutArray = [labelArray subarrayWithRange:arrayRange];
    float averageWith = width/layoutArray.count;
    
    
    for(int i=0;i<layoutArray.count;i++){
        UIView * tempView = [layoutArray objectAtIndex:i];
        tempView.framewidth = tempView.framewidth + averageWith;
        UIView * labelView = [[tempView subviews] lastObject];
        labelView.center = CGPointMake(tempView.framewidth / 2, tempView.frameheight / 2);
        if(i==0){
            continue;
        }else{
            tempView.frameleft = tempView.frameleft + averageWith*i;
        }
    }
}

#pragma mark 点击热门标签
-(void)taplabel:(UIGestureRecognizer*)gesture
{
    CusLab * label = (CusLab *)gesture.view;
    
    for (int i = 0 ; i < _allViewArray.count;  i ++) {
        UIView *tempView = [_allViewArray objectAtIndex:i];
        CusLab * labelView = [[tempView subviews] lastObject];
//        if (gesture.view != tempView) {
//            tempView.backgroundColor =  RGB(240, 240, 240);
//            labelView.textColor = RGB(76, 76, 76);
//        } else {
//            tempView.backgroundColor = RGB(209, 209, 209);
//            labelView.textColor = RGB(76, 76, 76);
//        }
    }
    
    CusLab *lab = (CusLab *)[label viewWithTag:label.tag + 100];
    
    if (self.hotTagClickBlock) {
        self.hotTagClickBlock(label.tag,lab);
    }
    
    
   
    if (self.hotTagNameBlock) {
        self.hotTagNameBlock(lab.text,lab);
    }
}

- (void) setSelectAtIndex:(NSInteger)index {
    
//    for (int i = 0 ; i < _allViewArray.count;  i ++) {
//        UIView *tempView = [_allViewArray objectAtIndex:i];
//        CusLab * labelView = [[tempView subviews] lastObject];
//        if (tempView.tag != index) {
//            tempView.backgroundColor = [UIColor clearColor];
//            labelView.textColor = [UIColor lightGrayColor];
//        } else {
//            tempView.backgroundColor = [UIColor lightGrayColor];
//            labelView.textColor = [UIColor whiteColor];
//        }
//    }
}

- (CGFloat)containHeight {
    return contentHeight;
}




-(void)setCartHotViewWithArray:(NSArray*)resultArray andSampleLabelFont:(CGFloat)fontSize height:(CGFloat)labelHeight andProductId:(NSString  *)productId{
    //change by dwwei
    if (_containView) {
        [_containView  removeFromSuperview];
        _containView = nil;
    }
    
    _containView = [[UIView alloc] initWithFrame:self.bounds];
    self.containView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.containView];
    UIFont * font = UIFontSize(fontSize);
    float height = 0;
    float labelWidth = 0;
    UIView * previousLabel = nil;
    
    _tempArray = [[NSMutableArray alloc] initWithCapacity:5];
    _allViewArray  = [[NSMutableArray alloc]init];
    for (int i=0;i<resultArray.count;i++) {
        //创建标签
        NSDictionary  *dic = [resultArray objectAtIndex:i];
        NSString  *labelTitle;
        if (productId) {
            //颜色
            labelTitle = [NSString  stringWithFormat:@"%@",[dic  objectForKey:@"colorText"]];
        }else {
            //尺码
            NSString *str = [dic objectForKey:@"specValue"];
            if ([str isEqual:[NSNull null]] || str == nil || str.length == 0) {
                labelTitle = @"均码";
            } else {
                labelTitle = [dic objectForKey:@"specValue"];
            }
            
        }
        
        CGSize size = [labelTitle sizeWithAttributes:@{NSFontAttributeName:font}];
        labelWidth = size.width + 24;
        height = labelHeight + 4;
        if (labelWidth > 300) {
            size = [labelTitle sizeWithFont:font constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
            labelWidth = 300;
            height = size.height + 5;
        }else if (labelWidth < 48){
            labelWidth = 48;
        }
        
        int tag = i + 100;
        
        UIImageView *adopLabel = [self createCartHotLabelWithPreviousLabel:previousLabel andDic:dic andWidth:labelWidth andHeight:height andLabTag:tag andProductId:productId];
        
        adopLabel.tag = i;
        //添加位置
        if (adopLabel.frameright > self.containView.frameright) { //下一行(需要换行)
            float width = self.containView.framewidth - previousLabel.frameright;
            //开始布局
            [self layoutLabelWithArray:_tempArray andWidth:width andIsLastLine:NO];
            [_tempArray removeAllObjects];
            adopLabel.frame = CGRectMake(0, previousLabel.framebottom+15.0f, adopLabel.framewidth, height);
            [self.containView addSubview:adopLabel];
        }else{//不变行（不需要换行）
            [_tempArray addObject:adopLabel];
            [self.containView addSubview:adopLabel];
        }
        previousLabel = adopLabel;
    }
    self.containView.frameheight = previousLabel.framebottom + 10.0f;
    
    if (previousLabel.framebottom > 0) {
        contentHeight = previousLabel.framebottom + 10;
    }else {
        contentHeight = height;
    }
    if (self.containViewHeightBlock) {
        self.containViewHeightBlock(self.containView.frameheight);
    }
    
    
    //如果是尺码数据只有一个且有库存  置为选中状态
    if (resultArray.count == 1 && !productId) {
        NSDictionary  *tempDic = [resultArray  objectAtIndex:0];
        if ([[tempDic  objectForKey:@"stock"] integerValue] > 0) {
            //判断是否有库存
            UIView *tempView = [_allViewArray objectAtIndex:0];
            CusLab * labelView = [[tempView subviews] lastObject];
            labelView.textColor = RGB(210, 16, 52);
            tempView.layer.borderColor = RGB(210, 16, 52).CGColor;
        }
    }
}


//创建标签
- (UIImageView *)createCartHotLabelWithPreviousLabel:(UIView*)previousLabel
                                         andDic:(NSDictionary*)dictionary
                                        andWidth:(float)width
                                       andHeight:(float)height
                                       andLabTag:(int)tag
                                       andProductId:(NSString  *)productId
{
    CGRect frame;
    if (previousLabel == nil) {
        frame = CGRectMake(0.0f, 0.0f, width, height);
        
    }else{
        frame = CGRectMake(previousLabel.frameright + 10, previousLabel.frametop, width, height);
    }
    CusLab *adopLabel = [[CusLab alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    adopLabel.highlightedTextColor = UIColorFromRGB(0xffffff);
    adopLabel.layer.masksToBounds=YES;
    adopLabel.layer.cornerRadius=12;
    adopLabel.layer.borderColor=UIColorFromRGB(0x999999).CGColor;
    adopLabel.layer.borderWidth=0.5f;
    adopLabel.backgroundColor = [UIColor clearColor];
    adopLabel.font = [UIFont systemFontOfSize:13];
    adopLabel.tag = tag;
    if (height > 27) {
        adopLabel.framewidth = width - 10;
    }
    adopLabel.textAlignment = NSTextAlignmentCenter;
    adopLabel.autoresizesSubviews = YES;
    adopLabel.numberOfLines = 0;
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:frame];
    adopLabel.framewidth = imageView.framewidth;
    imageView.backgroundColor = [UIColor whiteColor];
    imageView.userInteractionEnabled = YES;
    [imageView addSubview:adopLabel];
    
    
    if (productId) {
        //颜色
        NSString  *productIdStr = [NSString  stringWithFormat:@"%@",[dictionary  objectForKey:@"productId"]];
        if ([productIdStr  isEqualToString:[NSString  stringWithFormat:@"%@",productId]]) {
            adopLabel.textColor = RGB(210, 16, 52);
            imageView.layer.borderColor = RGB(210, 16, 52).CGColor;
        }else {
            adopLabel.textColor = RGB(76, 76, 76);
            imageView.layer.borderColor = RGB(209, 209, 209).CGColor;
        }
        adopLabel.text = [NSString  stringWithFormat:@"%@",[dictionary  objectForKey:@"colorText"]];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapColorlabel:) ];
        [imageView addGestureRecognizer:tap];
        
    }else {
        //尺码
        if ([[dictionary  objectForKey:@"stock"] integerValue] > 0) {
            //判断是否有库存
            adopLabel.textColor = RGB(76, 76, 76);
            imageView.layer.borderColor = RGB(209, 209, 209).CGColor;
            imageView.userInteractionEnabled = YES;
        }else {
            //没有库存让它不能点击
            adopLabel.textColor = [UIColor  lightGrayColor];
            imageView.layer.borderColor = [UIColor  lightGrayColor].CGColor;
            imageView.userInteractionEnabled = NO;
        }
        
        NSString *str = [dictionary objectForKey:@"specValue"];
        if ([str isEqual:[NSNull null]] || str == nil || str.length == 0) {
            adopLabel.text = @"均码";
        } else {
            adopLabel.text = [dictionary objectForKey:@"specValue"];
        }
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCartlabel:) ];
        [imageView addGestureRecognizer:tap];
    }
    
    [_allViewArray addObject:imageView];
    
    return imageView ;
}

-(void)tapColorlabel:(UIGestureRecognizer*)gesture
{
    CusLab * label = (CusLab *)gesture.view;
    
    CGRect rect;
    
    for (int i = 0 ; i < _allViewArray.count;  i ++) {
        UIView *tempView = [_allViewArray objectAtIndex:i];
        CusLab * labelView = [[tempView subviews] lastObject];
        if (gesture.view != tempView) {
            tempView.layer.borderColor =RGB(209, 209, 209).CGColor;
            labelView.textColor = RGB(76, 76, 76);
        } else {
            tempView.layer.borderColor = RGB(210, 16, 52).CGColor;
            labelView.textColor = RGB(210, 16, 52);
        }
    }
    
    CusLab *lab = (CusLab *)[label viewWithTag:label.tag + 100];
    
    if (self.hotTagClickBlock) {
        self.hotTagClickBlock(label.tag,lab);
    }

    if (self.hotTagNameBlock) {
        self.hotTagNameBlock(lab.text,lab);
    }
}

-(void)tapCartlabel:(UIGestureRecognizer*)gesture
{
    CusLab * label = (CusLab *)gesture.view;
    
    CGRect rect;
    
    for (int i = 0 ; i < _allViewArray.count;  i ++) {
        UIView *tempView = [_allViewArray objectAtIndex:i];
        CusLab * labelView = [[tempView subviews] lastObject];
        if (gesture.view != tempView) {
            if(tempView.userInteractionEnabled){
                tempView.layer.borderColor =RGB(209, 209, 209).CGColor;
                labelView.textColor = RGB(76, 76, 76);
            }
       
        } else {
            tempView.layer.borderColor = RGB(210, 16, 52).CGColor;
            labelView.textColor = RGB(210, 16, 52);
         
            rect = [self convertRect:tempView.frame toView:self.superview.superview.superview.superview.superview];
            
            if (self.hotCartTagClickBlock) {
                self.hotCartTagClickBlock(rect,label.tag);
            }
        }
    }    
    
        CusLab *lab = (CusLab *)[label viewWithTag:label.tag + 100];
    if (self.hotTagClickBlock) {
        self.hotTagClickBlock(label.tag,lab);
    }
    

    
    if (self.hotTagNameBlock) {
        self.hotTagNameBlock(lab.text,lab);
    }
}


@end
